// 成员工时详情页JavaScript功能

// 返回列表页
function goBack() {
    window.location.href = '/dashboard';
}

// 加载成员工时详情数据
async function loadMemberWorktimeDetail(name, period) {
    try {
        const params = new URLSearchParams({
            name: name,
            period: period
        });
        
        const response = await fetch(`/api/member-worktime-detail?${params}`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 更新成员概览信息
        updateMemberOverview(data);
        
        // 更新工时分类统计
        updateWorktimeCategoryStats(data);
        
        // 更新项目投入统计
        updateProjectStats(data.project_summary, data.total_project_worktime);
        
        // 更新项目详情
        updateProjectsDetails(data.project_summary, data.system_summary, data.requirement_summary);
        
    } catch (error) {
        console.error('加载成员工时详情失败:', error);
        showMessage('加载成员工时详情失败: ' + error.message, 'error');
    }
}

// 更新成员概览信息
function updateMemberOverview(data) {
    document.getElementById('member-name').textContent = data.name;
    document.getElementById('statistics-period').textContent = data.statistics_period;
    document.getElementById('member-role').textContent = data.role || '未指定';
    document.getElementById('saturation-rate').textContent = data.saturation_rate ? data.saturation_rate.toFixed(1) + '%' : '-';
    document.getElementById('used-worktime').textContent = data.used_worktime.toFixed(1) + ' 人天';
    document.getElementById('project-worktime').textContent = data.total_project_worktime.toFixed(1) + ' 人天';
    
    // 更新页面标题
    document.getElementById('member-title').textContent = `${data.name} - 工时统计详情`;
}

// 更新工时分类统计
function updateWorktimeCategoryStats(data) {
    const tbody = document.getElementById('worktime-category-tbody');
    tbody.innerHTML = '';
    
    const totalWorktime = data.used_worktime || 0;
    
    const categories = [
        { name: '需求工时', value: data.requirement_worktime || 0 },
        { name: '工单工时', value: data.ticket_worktime || 0 },
        { name: 'Bug工时', value: data.bug_worktime || 0 },
        { name: '项目工时', value: data.total_project_worktime || 0 }
    ];
    
    categories.forEach(category => {
        if (category.value > 0) {
            const percentage = totalWorktime > 0 ? ((category.value / totalWorktime) * 100).toFixed(1) : 0;
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${category.name}</td>
                <td>${category.value.toFixed(1)} 人天</td>
                <td>${percentage}%</td>
            `;
            tbody.appendChild(row);
        }
    });
    
    if (tbody.children.length === 0) {
        tbody.innerHTML = '<tr><td colspan="3" style="text-align: center; color: #6c757d;">暂无工时分类数据</td></tr>';
    }
}

// 更新项目投入统计
function updateProjectStats(projectSummary, totalProjectWorktime) {
    const tbody = document.getElementById('project-stats-tbody');
    tbody.innerHTML = '';
    
    projectSummary.forEach(project => {
        const percentage = totalProjectWorktime > 0 ? ((project.total_worktime / totalProjectWorktime) * 100).toFixed(1) : 0;
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${project.project_name}</td>
            <td>${project.total_worktime.toFixed(1)} 人天</td>
            <td>${project.system_count}</td>
            <td>${project.requirement_count}</td>
            <td>${percentage}%</td>
        `;
        tbody.appendChild(row);
    });
    
    if (projectSummary.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #6c757d;">暂无项目投入数据</td></tr>';
    }
}

// 更新项目详情
function updateProjectsDetails(projectSummary, systemSummary, requirementSummary) {
    const container = document.getElementById('projects-container');
    container.innerHTML = '';
    
    projectSummary.forEach(project => {
        // 获取该项目下的系统
        const projectSystems = systemSummary.filter(system => 
            system.project_name === project.project_name
        );
        
        // 创建项目卡片
        const projectCard = document.createElement('div');
        projectCard.className = 'system-card';
        
        // 项目基本信息
        const projectHeader = document.createElement('div');
        projectHeader.className = 'system-header';
        projectHeader.innerHTML = `
            <h4>${project.project_name}</h4>
            <div class="system-stats">
                <span class="stat-item">系统数: ${project.system_count}</span>
                <span class="stat-item">需求数: ${project.requirement_count}</span>
                <span class="stat-item">工时: ${project.total_worktime.toFixed(1)} 人天</span>
            </div>
        `;
        
        // 系统列表
        const systemsList = document.createElement('div');
        systemsList.className = 'requirements-list';
        systemsList.innerHTML = `
            <h5>系统列表 (${projectSystems.length}个)</h5>
            <div class="requirements-tags">
                ${projectSystems.map(system => 
                    `<span class="requirement-tag">${system.system_name} (${system.total_worktime.toFixed(1)}人天)</span>`
                ).join('')}
            </div>
        `;
        
        // 需求详情表格
        const detailTable = document.createElement('div');
        detailTable.className = 'detail-table-container';
        
        let tableHTML = `
            <h5>需求详情</h5>
            <div class="requirements-detail">
        `;
        
        // 按系统分组显示需求
        projectSystems.forEach(system => {
            const systemRequirements = requirementSummary.filter(req => 
                req.project_name === project.project_name && req.system_name === system.system_name
            );
            
            if (systemRequirements.length > 0) {
                tableHTML += `
                    <div class="requirement-group">
                        <div class="requirement-header">
                            <strong>${system.system_name}</strong>
                            <span class="requirement-worktime">系统工时: ${system.total_worktime.toFixed(1)} 人天</span>
                        </div>
                        <table class="data-table requirement-table">
                            <thead>
                                <tr>
                                    <th>需求内容</th>
                                    <th>工时</th>
                                    <th>需求类型</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                systemRequirements.forEach(req => {
                    tableHTML += `
                        <tr>
                            <td>${req.work_content}</td>
                            <td>${req.total_worktime.toFixed(1)} 人天</td>
                            <td>${req.requirement_type}</td>
                            <td><span class="status-badge status-${getStatusClass(req.status)}">${req.status}</span></td>
                        </tr>
                    `;
                });
                
                tableHTML += `
                            </tbody>
                        </table>
                    </div>
                `;
            }
        });
        
        tableHTML += '</div>';
        detailTable.innerHTML = tableHTML;
        
        // 组装项目卡片
        projectCard.appendChild(projectHeader);
        projectCard.appendChild(systemsList);
        projectCard.appendChild(detailTable);
        
        container.appendChild(projectCard);
    });
    
    if (projectSummary.length === 0) {
        container.innerHTML = '<div style="text-align: center; color: #6c757d; padding: 20px;">暂无项目数据</div>';
    }
}

// 获取状态样式类
function getStatusClass(status) {
    if (!status) return 'default';
    
    const statusStr = status.toLowerCase();
    if (statusStr.includes('完成') || statusStr.includes('上线')) {
        return 'completed';
    } else if (statusStr.includes('进行') || statusStr.includes('开发')) {
        return 'in-progress';
    } else {
        return 'default';
    }
}

// 显示消息提示
function showMessage(message, type) {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 10px 20px;
        border-radius: 4px;
        color: white;
        z-index: 1000;
        ${type === 'error' ? 'background-color: #dc3545;' : 'background-color: #28a745;'}
    `;
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 3000);
}